package net.chasing.androidbaseconfig.util;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.AsyncTask;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.concurrent.atomic.AtomicReference;

public class MediaUtils {

    /**
     * 获取视频的第一帧图片
     * 如果是用于列表的情况，需要注意：
     * 在请求回调的时候，判断ImageView加载的是否是原来的drawable，进行判断在请求第一帧的过程中加载了别的图片，
     * 则请求第一帧回调之后就不用设置到ImageView上了
     */
    public static void getImageForVideo(Context context, String videoPath, OnLoadVideoImageListener listener) {
        File f = getOutputMediaFile(context, videoPath);
        if (f.exists()) {
            if (listener != null) {
                if (context instanceof Activity)
                    if (((Activity) context).isFinishing()) return;
                listener.onLoadImage(context, f);
            }
        } else {
            LoadVideoImageTask task = new LoadVideoImageTask(context, listener);
            task.execute(videoPath);
        }
    }

    /**
     * Create a File for saving an image or video
     */
    private static File getOutputMediaFile(Context context, String path) {
        // Create a media file name
        path = path.replace("\\", "/");
        String fileName = path.substring(path.lastIndexOf('/') + 1, path.lastIndexOf('.'));
        return new File(FileUtils.getVideoThumbnailPath(context) + fileName + ".jpg_");
    }

    public static class LoadVideoImageTask extends AsyncTask<String, Integer, File> {
        private final AtomicReference<OnLoadVideoImageListener> listener = new AtomicReference<>();
        private final AtomicReference<Context> context = new AtomicReference<>();

        LoadVideoImageTask(Context context, OnLoadVideoImageListener listener) {
            super();
            this.listener.set(listener);
            this.context.set(context);
        }

        public String getContextName() {
            if (context.get() == null) return "";
            else return context.get().getClass().getSimpleName();
        }

        public void release() {
            cancel(true);
            listener.set(null);
            context.set(null);
        }

        @Override
        protected File doInBackground(String... params) {
            if (context.get() == null) return null;
            MediaMetadataRetriever mmr = null;
            String path = params[0];
            //保存图片
            File f = getOutputMediaFile(context.get(), path);
            if (f.exists()) {
                return f;
            }
            try {
                if (path.startsWith("http")) { //获取网络视频第一帧图片
                    mmr = new MediaMetadataRetriever();
                    mmr.setDataSource(path, new HashMap<>());
                } else //本地视频，Glide可以直接加载本地视频，会显示第一帧
                    return new File(path);
                Bitmap bitmap = mmr.getFrameAtTime();

                FileOutputStream out = new FileOutputStream(f);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
                out.flush();
                out.close();
                bitmap.recycle();
            } catch (Exception e) {
                e.printStackTrace();
                f = null;
            } finally {
                try {
                    if (mmr != null)
                        mmr.release();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return f;
        }

        @Override
        protected void onPostExecute(File file) {
            super.onPostExecute(file);
            if (context.get() == null) return;
            if (context.get() instanceof Activity)
                if (((Activity) context.get()).isFinishing()) return;
            if (listener.get() != null) {
                listener.get().onLoadImage(context.get(), file);
            }
        }
    }

    public interface OnLoadVideoImageListener {
        void onLoadImage(Context context, File file);
    }
}
